import sqlite3
import os



class SqliteHandler:

    def __init__(self, path):
        self.conn = sqlite3.connect(path)
        # print("Opened database successfully")
        self.c = self.conn.cursor()

    def close(self):
        # self.conn.commit()
        self.conn.close()
        # print("Close database successfully")
    
    def select(self, table, *args, **kwargs):
        # kwargs: flag为list 返回 list
        flag = kwargs.get('flag')
        tostring = kwargs.get('tostring', False)
        if len(args) == 0:
            names = '* '
        else:
            names = ''
            for i in args:
                names += i
                names += ' '
        data = self.c.execute("SELECT " + names + 'FROM ' + table)

        if flag != 'list':
            return data
        else:
            return self.cursor2list(data, tostring)

    def cursor2list(self, cursor, tostring=False):
        # 将cursor可迭代对象转换为list
        mylist = []
        for i in cursor:
            temp = []
            for j in i:
                if tostring:
                    j = str(j)
                temp.append(j)
            mylist.append(temp)

        return mylist

        

if __name__ == "__main__":
    BASE_DIR = os.path.dirname(os.path.abspath(__file__))
    path = os.path.join(BASE_DIR, 'test.db')
    sql = SqliteHandler(path)
    data = sql.select('opt_transfees')
    print(data)
    for i in data:
        print(i)
    sql.close()